import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import axios from 'axios'

export const useScreenStore = defineStore('screen', () => {
  const config = reactive({
    mode: 'auto',
    interval: 10,
    currentPage: '首页',
    pages: ['首页', '数据概览', '实时监控', '统计分析', '系统设置']
  })

  const isConnected = ref(false)
  const lastUpdate = ref('')

  // 获取配置
  const fetchConfig = async () => {
    try {
      const response = await axios.get('/api/screen/config')
      Object.assign(config, response.data)
      lastUpdate.value = new Date().toLocaleString()
    } catch (error) {
      console.error('获取配置失败:', error)
    }
  }

  // 更新配置
  const updateConfig = async (newConfig) => {
    try {
      const response = await axios.post('/api/screen/config', newConfig)
      Object.assign(config, response.data)
      lastUpdate.value = new Date().toLocaleString()
    } catch (error) {
      console.error('更新配置失败:', error)
    }
  }

  // 切换页面
  const switchPage = async (pageName) => {
    try {
      await axios.post(`/api/screen/switch/${pageName}`)
      config.currentPage = pageName
      lastUpdate.value = new Date().toLocaleString()
    } catch (error) {
      console.error('切换页面失败:', error)
    }
  }

  // 设置模式
  const setMode = async (mode) => {
    try {
      await axios.post(`/api/screen/mode/${mode}`)
      config.mode = mode
      lastUpdate.value = new Date().toLocaleString()
    } catch (error) {
      console.error('设置模式失败:', error)
    }
  }

  // 设置间隔时间
  const setInterval = async (interval) => {
    try {
      await axios.post(`/api/screen/interval/${interval}`)
      config.interval = interval
      lastUpdate.value = new Date().toLocaleString()
    } catch (error) {
      console.error('设置间隔时间失败:', error)
    }
  }

  return {
    config,
    isConnected,
    lastUpdate,
    fetchConfig,
    updateConfig,
    switchPage,
    setMode,
    setInterval
  }
}) 